#!D:\Python27\python.exe
# -*- coding: utf-8 -*-
'''
    Implements abstract command

    :copyright: (c) 2014 by Duxin.
'''

import cgi
import Cookie
import os

import sessions
import db.db_manager as dbm

class Command(object):
    '''
        Command is the base class of all specical Commands. This class can deal with the session
        and parameter problems. So the derived class can foues on their own logical.
        Any derived class must implements two interfaces: 1. is_param_right, which is responsible 
        for parameter checking. 2. execute, which is responsible for doing some specical task.
    '''
    
    def __init__(self):
        self.form = cgi.FieldStorage()
       
        cookie = Cookie.SimpleCookie()
        string_cookie = os.environ.get('HTTP_COOKIE')
        
        session = None
        
        # If already existent session
        if string_cookie:
            cookie.load(string_cookie)
            sid = cookie['sid'].value
            session = sessions.Session.get_session(sid)
            cookie['sid']['path'] = '/'
        
        if session is None:
            session = sessions.Session()
            # Set the sid in the cookie
            cookie['sid'] = session.get_session_id()
            # Will expire in one week
            cookie['sid']['expires'] = 7 * 24 * 60 * 60
            cookie['sid']['path'] = '/'
        
        self.session = session
        self.cookie = cookie
        
        print self.cookie
        print 'Content-type: text/html\n\n'
    
    def __del__(self):
        dbm.SessionDAO.persist(self.session)
    
    def get_session(self):
        return self.session
    
    def get_param(self, key):
        form = cgi.FieldStorage()
        
        if form.has_key(key):
            return form[key].value 
        else:
            return None

    def write(self, str):        
        print str

    def is_param_right(self):
        pass
    
    def execute(self):
        raise RuntimeException("not implemented")
